#include <QDir>
#include <QFile>
#include <QDebug>

#include "parser.h"

Parser::Parser(QObject *parent) :
    QObject(parent), mItemHandler(0), state(UNKNOWN)
{
}

Parser::Parser(ItemHandler *itemHandler, QObject *parent) :
    QObject(parent), mItemHandler(itemHandler), state(UNKNOWN)
{
}

void Parser::parse(QString fileName)
{
    if(fileName.isEmpty())
        fileName = "settings.conf";
    QFile file(fileName);
    if(file.exists() && file.open(QIODevice::ReadOnly)) {
        QString line;
        while(!(line = QString(file.readLine()).trimmed()).isEmpty())
        {
            if(0 == QString::compare(line, RESOURCES, Qt::CaseInsensitive) )
            {
                state = RESOURCE;
                continue;
            }
            else if(0 == QString::compare(line, CATEGORIES, Qt::CaseInsensitive) )
            {
                state = CATEGORY;
                continue;
            }

            if( RESOURCE == state )
            {
                readResource(line);
            } else if ( CATEGORY == state )
            {
                readCategory(line);
            } else
            {
                qDebug() << "Don't know what to do!";
            }
        }
    }

    file.close();
}

void Parser::readResource(QString line)
{
    Q_ASSERT(line.length() != 0);

    Resource *resource = 0;
    QStringList list = line.split("\\");
    int id = list.at(0).toInt();
    if(0 == mItemHandler->getResource(id))
    {
        resource = new Resource(this);
        mItemHandler->addResource(resource);
    } else
    {
        resource = mItemHandler->getResource(id);
    }

    QStringList list2 = list.at(1).split("=");
    if( 0 == QString::compare(IMAGE, list2.at(0)) )
    {
        QUrl url(list2.at(1).trimmed());
        resource->setUrl(url);
    } else if( 0 == QString::compare(NAME, list2.at(0)) )
    {
        resource->setName(list2.at(1).trimmed());
    }

}

void Parser::readCategory(QString line)
{
    Q_ASSERT(line.length() != 0);

    Category *category = 0;
    QStringList list = line.split("\\");
    int id = list.at(0).toInt();
    if(mItemHandler->getCategory(id) == 0)
    {
        category = new Category(this);
        mItemHandler->addCategory(category);
    }
    else
        category = mItemHandler->getCategory(id);
    QStringList list2 = list.at(1).split("=");
    if( 0 == QString::compare(COLOR, list2.at(0)) )
    {
        QStringList list3 = list2.at(1).split(",");
        QColor color(list3.at(0).toInt(), list3.at(1).toInt(), list3.at(2).toInt());
        category->setColor(color);
    } else if( 0 == QString::compare(NAME, list2.at(0)) )
    {
        category->setName(list2.at(1).trimmed());
    }
}

